package com.javaex.book.controller;

import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.javaex.book.pojo.Book;
import com.javaex.book.pojo.Cart;
import com.javaex.book.pojo.CartItem;
import com.javaex.book.services.BookService;
import com.javaex.book.utils.Constants;
import com.javaex.book.utils.ReturnResult;

@Controller
@ResponseBody
@RequestMapping("/cart")
public class CartController {
	
	private static final Logger logger = LoggerFactory.getLogger(CartController.class);
	
	private final BookService bookService;
	
	@Autowired
	public CartController(BookService bookService) {
		this.bookService = bookService;
	}

	/**
	 * 添加商品到购物车
	 * @param bookId 图书id
	 * @param session
	 * @return 添加结果
	 */
	@PostMapping("/{bookId}")
	public ReturnResult add(@PathVariable("bookId") Integer bookId, HttpSession session) {
		Book book = bookService.getBookById(bookId);
		CartItem cartItem = new CartItem(book.getId(), book.getName(), 1, book.getPrice());
		logger.info("添加商品到购物车：{}", cartItem);
		Cart cart = (Cart) session.getAttribute(Constants.CART_IN_SESSION_KEY);
		if (cart == null) {
			cart = new Cart();
			session.setAttribute(Constants.CART_IN_SESSION_KEY, cart);
		}
		cart.add(cartItem);
		return ReturnResult.success("添加成功", cart.getTotalCount());
	}
	
	/**
	 * 获取购物车商品数量
	 * @param session 
	 * @return 购物车商品数量
	 */
	@GetMapping("/count")
	public Integer getCartItemCount(HttpSession session) {
		Cart cart = (Cart) session.getAttribute(Constants.CART_IN_SESSION_KEY);
		if (cart == null) {
			return 0;
		}
		return cart.getTotalCount();
	}
	
	/**
	 * 获取购物车
	 * @param session
	 * @return 购物车
	 */
	@GetMapping()
	public Cart getCart(HttpSession session) {
		// token用于防止表单重复提交
		String token = UUID.randomUUID().toString().replace("-", "");
		session.setAttribute(Constants.FORM_SUBMIT_NOT_REPEAT_KEY, token);
		return (Cart) session.getAttribute(Constants.CART_IN_SESSION_KEY);
	}
	
	/**
	 * 修改购物车商品数量
	 * @param id 商品id
	 * @param count 商品数量
	 * @return 修改结果
	 */
	@PutMapping()
	public ReturnResult updateCount(Integer id, Integer count, HttpSession session) {
		logger.info("修改商品数量：id={}, count={}", id, count);
		Cart cart = (Cart) session.getAttribute(Constants.CART_IN_SESSION_KEY);
		if (cart == null) return ReturnResult.fail("修改失败");
		
		cart.update(id, count);
		return ReturnResult.success("修改成功", cart);
	}
	
	/**
	 * 清空购物车
	 */
	@DeleteMapping()
	public ReturnResult clearCart(HttpSession session) {
		logger.info("清空购物车");
		Cart cart = (Cart) session.getAttribute(Constants.CART_IN_SESSION_KEY);
		if (cart != null) {
			cart.clear();
		}
		return ReturnResult.success();
	}
	
	/**
	 * 从购物车删除商品
	 * @param id 商品id
	 * @param session 
	 * @return 删除结果，以及删除商品后的购物车
	 */
	@DeleteMapping("/{id}")
	public ReturnResult deleteCartItem(@PathVariable("id") Integer id, HttpSession session) {
		logger.info("从购物车删除商品：id={}", id);
		Cart cart = (Cart) session.getAttribute(Constants.CART_IN_SESSION_KEY);
		if (cart != null) {
			cart.delete(id);
		}
		return ReturnResult.success("删除成功", cart);
	}
}
